package com.yonyou.crm.sys.modules.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Date;

import org.springframework.stereotype.Service;

import com.yonyou.crm.common.biz.service.BaseBizServiceImpl;
import com.yonyou.crm.sys.modules.entity.LayoutVO;
import com.yonyou.crm.sys.modules.entity.RelationLayoutVO;
import com.yonyou.iuap.context.InvocationInfoProxy;

@Service
public class RelationLayoutBizServiceImpl extends BaseBizServiceImpl<RelationLayoutVO>{
	
	/**
	 * 删除所有相关对象布局
	 * 
	 * @return
	 */
		public int deleteLayouts(Long layoutId) {
			Map<String,Object> paramMap = new HashMap<String, Object>();
			String tenantIdStr = (String) InvocationInfoProxy.getTenantid();
			Long tenantId = Long.parseLong(tenantIdStr);
			paramMap.put("tenantId", tenantId);
			paramMap.put("layoutId", layoutId);
		   return dao.delete(RelationLayoutVO.class,"deleteAllLayouts",paramMap);
		}
	
	public int addLayouts(List<RelationLayoutVO> layoutVOs) {
		String tenantIdStr = (String) InvocationInfoProxy.getTenantid();
		Long tenantId = Long.parseLong(tenantIdStr);
		String userIdStr = (String)InvocationInfoProxy.getParameter("id");//用户id
		Long userId = Long.parseLong(userIdStr);
		Date now = new Date();
		for (int i =0; i<layoutVOs.size();i++) {
			RelationLayoutVO layoutVO = layoutVOs.get(i);		
			layoutVO.setSortOrder(i);
			layoutVO.setTenantId(tenantId);
			layoutVO.setSysCreatedTime(now);
			layoutVO.setSysModifiedTime(now);
			layoutVO.setSysCreatedUserId(userId);
			layoutVO.setSysModifiedUserId(userId);
		}
		return dao.saveSql(RelationLayoutVO.class, "batchInsertLayouts", layoutVOs);
	}
	
	public List<RelationLayoutVO> getLayoutList(Long tenantId,LayoutVO layout) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("tenantId", tenantId);
		paramMap.put("layoutId", layout.getId());
		List<RelationLayoutVO> relationLayoutVOs = dao.selectVoList(RelationLayoutVO.class, "ListRelationLayout",paramMap);
		List<Map<String, Object>> relationObjects =getRelatedObjects(layout.getObjId());
		for (RelationLayoutVO relationLayoutVO: relationLayoutVOs) {
			for (Map<String, Object> relationObject :relationObjects ) {
				if (relationLayoutVO.getRelObjId().equals(relationObject.get("relObjId"))) {
					relationLayoutVO.setName(relationObject.get("name").toString());
				}
			}
		}
		return relationLayoutVOs;
	}
	
	public List<Map<String, Object>> getRelatedObjects(Long objId) {
		Map<String, Object> relParamMap = new HashMap<String, Object>();
		relParamMap.put("objId", objId);
		List<Map<String, Object>> relationObjects = dao.selectList(RelationLayoutVO.class, "ListRelationObject", relParamMap);
		return relationObjects;
	}
	
}



